package com.yzq.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
@Component
public class MailUtils {
    private static final String FROM = "yezhiqiang2023@163.com";

    private final JavaMailSender javaMailSender;

    public MailUtils(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendHtmlMail(String to, String subject, String content) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            // 设置邮件内容为HTML格式
            String htmlContent = "<div style=\"padding: 20px; background: #f8f9fa;\">" +
                    "<h3 style=\"color: #2d3436;\">" + subject + "</h3>" +
                    "<p>您的验证码：<strong style=\"color: #e74c3c;\">" + content + "</strong></p>" +
                    "<p>有效期10分钟</p>" +
                    "</div>";

            helper.setSubject(subject);
            helper.setTo(to);
            helper.setFrom(FROM);
            helper.setText(htmlContent, true); // 第二个参数设置为true表示内容为HTML

            if (javaMailSender != null) {
                javaMailSender.send(mimeMessage);
                log.info("HTML邮件发送成功");
            } else {
                log.error("JavaMailSender 为 null");
            }
        } catch (MessagingException e) {
            log.error("发送HTML邮件时出错", e);
        }
    }
}
